package com.tangw.spring.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.tangw.spring.model.User;
import com.tangw.spring.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

	@Resource(name = "userService")
	private UserService service;

	@RequestMapping(value = "/count", method = RequestMethod.GET)
	public ModelAndView userCount() {
		int userCount = service.findAll().size();
		ModelAndView mv = new ModelAndView();
		mv.addObject("userCount", userCount);
		mv.setViewName("user/countUser");
		System.out.println("userCount:" + userCount);
		return mv;
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ModelAndView userList() {
		List<User> userList = service.findAll();
		ModelAndView mv = new ModelAndView();
		mv.addObject("userList", userList);
		mv.setViewName("user/listUser");
		System.out.println("userList:" + userList);
		return mv;
	}

	@RequestMapping(value = "/show/{id}", method = RequestMethod.GET)
	public ModelAndView userShow(@PathVariable("id") Integer id) {
		User userShow = service.findOne(id);
		ModelAndView mv = new ModelAndView();
		mv.addObject("userShow", userShow);
		mv.setViewName("user/showUser");
		System.out.println("userShow:" + userShow);
		return mv;
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public ModelAndView userAdd() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("user/addUser");
		System.out.println("addUser! get");
		return mv;
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String doUserAdd(@ModelAttribute("user") User user) {
		service.create(user);
		System.out.println("addUser! create");
		return "redirect:/user/list";
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public ModelAndView userEdit(@PathVariable("id") Integer id) {
		User userEdit = service.findOne(id);
		ModelAndView mv = new ModelAndView();
		mv.addObject("userEdit", userEdit);
		mv.setViewName("user/editUser");
		System.out.println("userEdit:" + userEdit);
		return mv;
	}

	@RequestMapping(value = "/save/{id}", method = RequestMethod.POST)
	public String saveEdit(@ModelAttribute("userEdit") User user,
			@PathVariable("id") Long id) {
		service.update(user);
		return "redirect:/user/list";
	}

	@RequestMapping(value = "/del/{id}", method = RequestMethod.GET)
	public String del(@PathVariable("id") Integer id) {
		service.deleteById(id);
		return "redirect:/user/list";
	}
}
